package cn.yedong.pet.service.impl;

import cn.yedong.pet.domain.PetType;
import cn.yedong.pet.mapper.PetTypeMapper;
import cn.yedong.pet.service.IPetTypeService;
import cn.yedong.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;
    /**
     * 获取类型树
     * @return
     */
    @Override
    public List<PetType> getTypeTree() {
        Map<Long, PetType> map = new HashMap<>();
        List<PetType> petTypes = petTypeMapper.loadAll();
        for (PetType petType : petTypes) {
            map.put(petType.getId(),petType);
        }

        List<PetType> typeTree = new ArrayList<>();
        for (PetType petType : petTypes) {
           if(petType.getParentId() == null){
               typeTree.add(petType);
           }else {
               PetType parentType = map.get(petType.getParentId());
               if(parentType != null){
                   parentType.getChildren().add(petType);
               }
           }
        }
        return typeTree;
    }
}
